﻿using System;
using System.IO;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Dialect;
using NHibernate.Mapping.ByCode;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

namespace Citi.HeadCount.Domain.NHibernate
{
    public class SessionFactory
    {
        private Configuration configuration;

        public ISessionFactory CreateSessionFactory()
        {
            //return Fluently.Configure()
            //    .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
            //    .Mappings(M => M.FluentMappings.AddFromAssemblyOf<SessionFactory>())
            //    .ExposeConfiguration(Cfg => configuration = Cfg)
            //    .BuildSessionFactory();

            //var dbFile = Path.Combine(HttpContext.Current.Server.MapPath("~"), @"Database\DEV_GocsAttributes.db")
            //   .Replace(@"Citi.HeadCount.WebUI\", "");

            var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["GOCDatabase"].ConnectionString;

            //var dbFile = (@"\\lacbra001fs0010\DATA_GRP1\FTOOLS\Databases\GOCs Attributes\DEV_GocsAttributes.db");
            
            var configuration = new Configuration();

            configuration.DataBaseIntegration(c =>
            {
                c.Dialect<SQLiteDialect>();
                c.ConnectionString = connectionString;
                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                c.BatchSize = 1;
            });
            configuration.AddMapping(GetMapping());
            configuration.SetProperty("adonet.batch_size", "1");
            return configuration.BuildSessionFactory();
        }

        private static HbmMapping GetMapping()
        {
            var mapper = new ModelMapper();
            mapper.AddMappings(typeof(EntityBase).Assembly.GetExportedTypes());

            return mapper.CompileMappingForAllExplicitlyAddedEntities();
        }
    }
}